import { showSuccessToast, showFailToast, showConfirmDialog, showDialog } from 'vant';
import BusinessStore from '@/stores/business';
import AddressStore from '@/stores/address';
import CartStore from '@/stores/cart';

export default {
    install(app)
    {
        // 初始化
        const BusinessStoreInit = BusinessStore();
        const AddressStoreInit = AddressStore();
        const CartStoreInit = CartStore();

        // 从pinia中获取数据
        const { business } = storeToRefs(BusinessStoreInit);
        const { address } = storeToRefs(AddressStoreInit);
        const { cart } = storeToRefs(CartStoreInit);
        
        // app == createApp == Vue应用
        let check = async () => 
        {
            // 获取用户ID和手机号
            let id = business.value.hasOwnProperty('id') ? business.value.id : 0
            let mobile = business.value.hasOwnProperty('mobile') ? business.value.mobile : ''

            // 调用接口，查询用户是否存在
            let result = await app.config.globalProperties.$POST({
                url: '/business/check',
                params: { id, mobile }
            });

            // 查找用户成功
            if (result.code === 1) 
            {
                // 更新pinia数据
                business.value = result.data;

                // 修改一下全局数据
                app.config.globalProperties.$business = business;

            } else if (result.code === 0)
            {
                // 清除缓存
                business.value = {}
                app.config.globalProperties.$business = business
            }

            return result;
        }

        // 在全局应用上面添加了一个自定义的属性
        app.config.globalProperties.$success = showSuccessToast;
        app.config.globalProperties.$fail = showFailToast;
        app.config.globalProperties.$confirm = showConfirmDialog;
        app.config.globalProperties.$check = check;
        app.config.globalProperties.$showDialog = showDialog;

        app.config.globalProperties.$business = business;
        app.config.globalProperties.$address = address;
        app.config.globalProperties.$cart = cart;
    }
}